package com.flash.media.ws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.flash.media.config.HttpUtil;
import com.flash.media.domain.RecordLog;
import com.flash.media.fegin.MongoFegin;
import com.flash.media.service.WsService;
import com.flash.media.utils.HTMLFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.atomic.AtomicInteger;

@ServerEndpoint("/websocket/chat/{loginName}")
@Component
public class ChatWebSocketEndPoint {

    //静态变量，用来记录当前在线连接数。应该把它设计成线程安全的。
    private static final AtomicInteger onlineNum = new AtomicInteger(0);
    //concurrent包的线程安全Set，用来存放每个客户端对应的Session对象。
    private static final Set<ChatWebSocketEndPoint> connections = new CopyOnWriteArraySet<>();

    private String loginName;
    private Session session;
    /**
     * 当有ws 客户端连接进来，调用的方法
     * @param session
     */

/*    private static RedisTemplate redisTemplate;*/

    private static WsService wsService;

/*    @Autowired
    public void setActionLogMapper(RedisTemplate redisTemplate) {
        ChatWebSocketEndPoint.redisTemplate = redisTemplate;
    }*/

    @Autowired
    public void setActionLogMapper2(WsService wsService) {
        ChatWebSocketEndPoint.wsService=wsService;
    }

    @OnOpen //创建一个websocket 就会执行OnOpen
    public void start(Session session, @PathParam("loginName")String loginName) {
        this.loginName = loginName;
        this.session = session;
        System.out.println("this:" + this);
        connections.add(this);

        onlineNum.incrementAndGet();//i++  ++i

        String msg = String.format("欢迎 %s(%s)加入，当前在线人数 %d",loginName,session.toString(),onlineNum.get());
        System.out.println(msg);

        broadcast(msg);//广播
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose //ws.close
    public void end(Session session,@PathParam("loginName")String loginName) {
        connections.remove(this);
        onlineNum.decrementAndGet();//i--
        String msg = String.format("%s(%s) 退出，当前在线人数 %d",loginName,session.toString(),onlineNum.get());
        System.out.println(msg);

        broadcast(msg);
    }

    /**
     * 接收到消息的监听方法
     * @param message
     */
    @OnMessage //ws.send
    public void incoming(Session session,String message,@PathParam("loginName")String loginName) {
        String msg = String.format("发送者%s(%s)发送消息： %s",loginName,session.toString(),message);
        System.out.println(msg);
        Date date = new Date();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format1 = format.format(date);
        String cs = wsService.cs();
        System.out.println(cs);
        RecordLog recordLog = new RecordLog();
        recordLog.setContent(message);
        recordLog.setRecordtime(format1);
        recordLog.setUsername(loginName);
        wsService.save(recordLog);
        String utterance = utterance(message);
        broadcast(loginName + ":" + HTMLFilter.filter(msg));

        recordLog.setContent(utterance);
        recordLog.setRecordtime(format1);
        recordLog.setUsername("智能客服");
        wsService.save(recordLog);
        broadcast("智能客服:" +utterance);
        /*        redisTemplate.opsForValue().set("cccc", "aa");*/
       /* if(message.equals("北京南站怎么走")){
            broadcast("智能客服:" + "打车去吧");//
            recordLog.setContent("打车去吧");
            recordLog.setRecordtime(format1);
            recordLog.setUsername("智能客服");
            wsService.save(recordLog);
            //查询问题答案 ES，查不到 “对不起，请转人工”
        }else {
            broadcast(loginName + ":" + HTMLFilter.filter(msg));
        }*/
    }





    public String utterance(String message) {
        // 请求URL
        String talkUrl = "https://aip.baidubce.com/rpc/2.0/unit/service/v3/chat";
        try {
            // 请求参数
            String params =  "{\"version\":\"3.0\",\"service_id\":\"S81130\",\"session_id\":\"\",\"log_id\":\"26227257\",\"request\":{\"terminal_id\":\"88888\",\"query\":\""+message+"\"}}";
            //String accessToken =AuthService.getAuth();
            String accessToken="24.e488cb026f38b241f3fa8dd8f373fcaa.2592000.1678190975.282335-30151487";
            String result = HttpUtil.post(talkUrl, accessToken, "application/json", params);
            /*JSONObject json = (JSONObject) JSON.toJSON(result);*/
            /*System.out.println(json);*/


            Map map = JSON.parseObject(result, Map.class);
            //String context = (String) map.get("result");
            /* Map map2 = JSON.parseObject(context, Map.class);*/
            String s = map.get("result").toString();
            Map map1 = JSON.parseObject(s, Map.class);
            String s1 = map1.get("context").toString();
            Map map2 = JSON.parseObject(s1, Map.class);
            String s2 = map2.get("SYS_PRESUMED_HIST").toString();
            String[] strings = JSON.parseObject(s2, String[].class);
            for (int i = 0; i <strings.length ; i++) {
                System.out.println(strings[i]);
            }
    /*        String[] split = s2.split(",");
            for (int i = 0; i <split.length ; i++) {
                System.out.println(split[i]);
            }*/
           /* Map map=new HashMap();
            map.get(result);*/
            JSONObject jsonObject = JSONObject.parseObject(result);
           /* Object result1 = jsonObject.get("result");
            System.out.println(jsonObject);*/


            return strings[1];
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }






    @OnError
    public void onError(Throwable t) throws Throwable {
        System.out.println("onError");
        t.printStackTrace();
    }

    /**
     * 广播消息
     * @param msg
     */
    private void broadcast(String msg) {
        for (ChatWebSocketEndPoint client : connections) {
            try {
                synchronized (client) {
                    client.session.getBasicRemote().sendText(msg);
                }
            } catch (IOException e) {
                connections.remove(client);
                try {
                    client.session.close();
                } catch (IOException e1) {
                    // Ignore
                }
                String message = String.format("* %s %s",
                        client.loginName, "has been disconnected.");
                broadcast(message);
            }
        }
    }
}
